package com.itxiuyixiu.volunteer.service;

import com.itxiuyixiu.entity.enums.AccountState;
import com.itxiuyixiu.entity.enums.AuthorityType;
import com.itxiuyixiu.entity.enums.DHUCollage;
import com.itxiuyixiu.entity.mapper.*;
import com.itxiuyixiu.entity.model.Admin;
import com.itxiuyixiu.entity.model.Organization;
import com.itxiuyixiu.entity.model.Teacher;
import com.itxiuyixiu.entity.model.User;
import com.itxiuyixiu.volunteer.dto.AdminModifyDetailsMessageParam;
import com.itxiuyixiu.volunteer.dto.UserModifyDetailMessageParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 网站运营者服务
 *
 * @author 黄磊
 * @date 2020/5/2
 */
@Slf4j
@Service
public class AdminService {
    @Resource
    private AdminReaderMapper adminReaderMapper;
    @Resource
    private AdminWriterMapper adminWriterMapper;
    @Resource
    private TeacherReaderMapper teacherReaderMapper;
    @Resource
    private TeacherWriterMapper teacherWriterMapper;
    @Resource
    private OrganizationWriterMapper organizationWriterMapper;
    @Resource
    private UserReadMapper userReadMapper;
    @Resource
    private UserWriterMapper userWriterMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 获取所有要审核的管理员信息（不包括审核失败的）
     *
     * @return 所有要审核的管理员信息
     */
    public List<Admin> getAllRegisterChecks() {
        List<Admin> admin = adminReaderMapper.findAllAdmin();
        return admin.stream().filter(e -> e.getAccountState().compare(AccountState.ADMIN_PASSED) < 0)
                .filter(e -> !e.getAccountState().equals(AccountState.FAILED))
                .collect(Collectors.toList());
    }

    /**
     * 获取所有未通过审核的管理员信息
     *
     * @return 所有要审核未通过的管理员信息
     */
    public List<Admin> findAllUnpassedAdmin() {
        return adminReaderMapper.findAllAdmin().stream()
                .filter(e -> e.getAccountState().equals(AccountState.FAILED))
                .collect(Collectors.toList());
    }

    /**
     * 管理员注册审核，审核通过的同时会创建相应的老师表或者志愿者组织表中创建字段
     *
     * @param adminId 管理员id
     * @param passed  是否通过审核
     * @return 返回值（0-审核通过，1-审核失败，2-未找到要审核的管理员信息）
     */
    public int registerCheck(Integer adminId, boolean passed) {
        Optional<Admin> adminOptional = adminReaderMapper.findAdminById(adminId);
        if (!adminOptional.isPresent()) {
            return 2;
        }
        Admin admin = adminOptional.get();
        if (!passed) {
            admin.setAccountState(AccountState.FAILED);
            adminWriterMapper.modifyAdminById(admin);
            return 1;
        }
        admin.setAccountState(AccountState.PASSED);
        adminWriterMapper.modifyAdminById(admin);
        log.info("管理员注册审核成功");
        if (admin.getAuthorities().contains(AuthorityType.ROLE_TEACHER_ADMIN)) {
            Teacher teacher = new Teacher();
            teacher.setTeacherName("teacherName");
            teacher.setAdminId(admin.getAdminId());
            teacherWriterMapper.saveTeacher(teacher);
            log.info("成功创建教师信息");
        } else if (admin.getAuthorities().contains(AuthorityType.ROLE_VOLUNTEER_ORGANIZATION_ADMIN)) {
            Organization organization = new Organization();
            organization.setOrgName("新建组织 - 未命名");
            organization.setAcademy(DHUCollage.DHU);
            organization.setAdminId(admin.getAdminId());
            organizationWriterMapper.saveOrganization(organization);
            log.info("成功创建组织信息");
        }
        return 0;
    }

    /**
     * 查看所有的管理员
     *
     * @return 所有的管理员信息
     */
    public List<Admin> findAllAdmin() {
        return adminReaderMapper.findAllAdmin();
    }

    /**
     * 根据adminId获取指定管理员信息
     *
     * @param adminId 管理员id
     * @return 管理员信息
     */
    public Admin findAdminById(Integer adminId) {
        Optional<Admin> adminOptional = adminReaderMapper.findAdminById(adminId);
        return adminOptional.orElse(null);
    }

    /**
     * 根据管理员id修改管理员信息
     *
     * <p>特殊用法：把管理员信息修改为审核未通过的话，可以起到禁止账号的目的<p/>
     *
     * @param adminDto 要修改的管理员信息
     * @return 修改状态（0 - 修改成功，1 - 管理员未找到）
     */
    public Integer modifyAdminMessage(Integer adminId, AdminModifyDetailsMessageParam adminDto) {
        Optional<Admin> adminOptional = adminReaderMapper.findAdminById(adminId);
        if (!adminOptional.isPresent()) {
            return 1;
        }
        Admin admin = adminOptional.get();
        admin.setAdminEmail(adminDto.getAdminEmail());
        admin.setNickName(adminDto.getNickName());
        admin.setAccountState(adminDto.getAccountState());
        adminWriterMapper.modifyAdminById(admin);
        log.info("成功修改管理员信息");
        return 0;
    }

    /**
     * 修改管理员的密码
     *
     * @param adminId  管理员id
     * @param password 密码
     * @return 修改状态（0-修改成功，1-管理员信息未找到）
     */
    public Integer modifyAdminPassword(Integer adminId, String password) {
        Optional<Admin> adminOptional = adminReaderMapper.findAdminById(adminId);
        if (!adminOptional.isPresent()) {
            return 1;
        }
        Admin admin = adminOptional.get();
        admin.setPassword(passwordEncoder.encode(password));
        adminWriterMapper.modifyAdminById(admin);
        log.info("成功修改管理员密码");
        return 0;
    }

    /**
     * 查找所有用户的信息
     *
     * @return 所有用户信息
     */
    public List<User> findAllUser() {
        return userReadMapper.findAllUser();
    }

    /**
     * 查找用户信息
     *
     * @param userId 用户id
     * @return 用户信息（不存在返回null）
     */
    public User findUserById(Integer userId) {
        return userReadMapper.findUserById(userId).orElse(null);
    }

    /**
     * 修改用户信息
     *
     * @param userDto 用户信息
     * @return 修改状态（0 - 修改成功，1 - 用户未找到）
     */
    public Integer modifyUserMessage(Integer userId, UserModifyDetailMessageParam userDto) {
        Optional<User> userOptional = userReadMapper.findUserById(userId);
        if (!userOptional.isPresent()) {
            return 1;
        }
        User user = userOptional.get();
        user.setUserEmail(userDto.getUserEmail());
        user.setNickName(userDto.getNickName());
        userWriterMapper.modifyUserById(user);
        log.info("成功修改用户信息");
        return 0;
    }

    /**
     * 修改用户的密码
     *
     * @param userId   用户id
     * @param password 密码
     * @return 修改状态（0-修改成功，1-用户信息未找到）
     */
    public Integer modifyUserPassword(Integer userId, String password) {
        Optional<User> userOptional = userReadMapper.findUserById(userId);
        if (!userOptional.isPresent()) {
            return 1;
        }
        User user = userOptional.get();
        user.setPassword(passwordEncoder.encode(password));
        userWriterMapper.modifyUserById(user);
        log.info("成功修改用户密码");
        return 0;
    }

}
